#定义除了控制器之外的类
from datetime import datetime
from airconfig.config import config
import json
from django.http import HttpResponse, JsonResponse
from django.core import signing
from common.models import Detail, Customer
# Create your models here.

# 房间
class Room():
    def __init__(self):
        self.roomid=config.room_list[0]
        self.checkinT=datetime.now()
        self.onoff=0 #0是关机，1是开机
        self.mode=config.default_work_mode
        self.totalCost=0
        self.freeRate=config.fee_rates
        self.default_TargetTemp_cold=config.default_goal_temp_cold
        self.default_TargetTemp_hot=config.default_goal_temp_hot
        self.temp_highLimit=config.hot_sup
        self.temp_lowLimit=config.cold_sub
        self.default_FanSpeed=config.default_fan_speed
        self.lastoff=None
        self.currenttemp=config.default_current_temp
    def get_current_temp(self):
        if self.lastoff==None:
            self.currenttemp=config.default_current_temp
        else:
            pass_minute=((datetime.now()-self.lastoff).seconds)/60
            if self.currenttemp>=config.default_current_temp:  #当前当前温度大于室温
                temp=self.currenttemp-pass_minute*config.temp_rate
                if temp<config.default_current_temp:
                    self.currenttemp=config.default_current_temp
                else:
                    self.currenttemp=temp
            else:      #降温回温
                temp = self.currenttemp + pass_minute * config.temp_rate
                if temp > config.default_current_temp:
                    self.currenttemp = config.default_current_temp
                else:
                    self.currenttemp = temp
        return self.currenttemp
# 顾客
class Customer1():
    def signup(self,request):
        request.params = json.loads(request.body)
        user = request.params["user"]
        passwd = request.params["passwd"]
        print("receiving request:customer signup,roomid:user")
        return_value = dict()
        result = Customer.objects.filter(rid=user,password=passwd).values_list('checkinDate', flat=True)
        if result:
            return_value['error_code'] = 0
            checkinDate=result[len(result)-1]
            checkinDate=str(int(checkinDate.timestamp()))
            token = str(user) + '|' + str(signing.dumps({'rid': user}))+','+checkinDate+'|'+str(signing.dumps({'checkinDate': checkinDate}))
            print(token)
            data = {'error_code': 0, 'data': {'token': token}}
            return HttpResponse(content=data, content_type="application/json")
        else:
            return_value['error_code'] = 1
            ret = json.dumps(return_value)
            return HttpResponse(content=ret, content_type="application/json")
